package org.example;

import lombok.extern.slf4j.Slf4j;
import org.example.Util.Sleeper;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


@Slf4j(topic = "c.Main")
public class Main {
    static final Object room = new Object();
    static boolean hasCigarette = false;
    static boolean hasTakeout = false;
    static ReentrantLock ROOM = new ReentrantLock();
    static Condition waitCigarette = ROOM.newCondition();//等待烟的休息室
    static Condition waitTakeout = ROOM.newCondition();//等待外卖的休息室

    public static void main(String[] args) {

        new Thread(() -> {
            ROOM.lock();
            try {
                log.debug("有烟没？[{}]", hasCigarette);
                if (!hasCigarette) {
                    log.debug("没烟，先歇会！");
                    try {
                        waitCigarette.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("可以开始干活了");
            } finally {
                ROOM.unlock();
            }

        }, "小南").start();
        new Thread(() -> {
            ROOM.lock();
            try{
                log.debug("外卖送到没？[{}]", hasTakeout);
                if (!hasTakeout) {
                    log.debug("没外卖，先歇会！");
                    try {
                        waitTakeout.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("可以开始干活了");
            }finally {
                ROOM.unlock();
            }
        }, "小女").start();

        Sleeper.sleep(1);
        new Thread(() -> {
            ROOM.lock();
            try {
                hasTakeout = true;
                log.debug("外卖到了噢！");
                waitTakeout.signal();
            }finally {
                ROOM.unlock();
            }

        }, "送外卖的").start();

        Sleeper.sleep(1);
        new Thread(() -> {
            ROOM.lock();
            try {
                hasCigarette = true;
                log.debug("烟到了噢！");
                waitCigarette.signal();
            }finally {
                ROOM.unlock();
            }

        }, "送烟的").start();
    }
}